package org.insia.smartposse.mapping.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.insia.smartposse.manager.ApplicationManager;
import org.insia.smartposse.manager.SkillManager;
import org.insia.smartposse.manager.UserManager;
import org.insia.smartposse.mapping.Users;
import org.insia.smartposse.mapping.base.BaseUsersDAO;


public class UsersDAO extends BaseUsersDAO implements org.insia.smartposse.mapping.dao.iface.UsersDAO {

	public static final int FREELANCE = 1;

	public UsersDAO () {}

	public UsersDAO (Session session) {
		super(session);
	}

	/**
	 * Search a User with a login
	 *
	 * @param login
	 * @return org.insia.smarposse.mapping.Users
	 */
	public Users getByLogin(String login) {
		Session s = null;
		try {
			s = getSession();
			return (Users) s.createCriteria(Users.class).add(
					Restrictions.like("Login", login)).uniqueResult();
		} finally {
			closeSession(s);
		}
	}

	/**
	 * Return the number of Job Where the freelancer is accept
	 *
	 * @param user
	 * @param session
	 * @return
	 */
	public int nbJobAccept(UserManager user, Session session) {
		return session.createCriteria(getReferenceClass())
					.add(Restrictions.eq("Id", user.getId()))
					.createCriteria("FreelanceApplicationList")
						.add(Restrictions.eq("Accept", ApplicationManager.ACCEPT))
					.list().size();
	}

	/**
	 * Create criteria for all Value
	 *
	 * @param session
	 * @return
	 */
	private Criteria critAll(Session session) {
		Criteria crit = session.createCriteria(getReferenceClass());
		if (null != getDefaultOrder())
			crit.addOrder(getDefaultOrder());
		return crit;
	}

	/**
	 * Search a list of User
	 *
	 * @param session
	 * @param usertype
	 * @param name
	 * @param skill
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Users> search(Session session, int usertype, String name,
			SkillManager skill) {
		Criteria crit = critAll(session);
		if (FREELANCE == usertype){
			crit.add(Restrictions.eq("Freelance", true));
		}

		if (null != name && !name.equals("")){
			crit.add(Restrictions.or(
					Restrictions.like("FirstName", "%" + name + "%"),
					Restrictions.like("LastName", "%" + name + "%")
					));
		}

		if (null != skill){
			crit.createCriteria("FreelanceSkillsList")
				.add(Restrictions.eq("Skill", skill.getSkill()));
		}

		return crit.list();
	}


}